<?php

namespace App\Http\Controllers\Wxpay;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Services\WeChatPayService;
use Illuminate\Support\Str;
class PaymentController extends Controller {
    public function create(Request $request) {
        $request->validate(['amount' => 'required|numeric|min:0.01']);

        try {
            $result = WeChatPayService::createH5Order(
                'WX'.date('YmdHis').Str::random(6),
                $request->amount,
                '商品购买'
            );

            return redirect($result['h5_url']);
        } catch (Exception $e) {
            return back()->withErrors($e->getMessage());
        }
    }

    public function notify(Request $request,WeChatPayService $weChatPayService) {
        return $weChatPayService->initConfig()->getServer()->with(function($message, \Closure $next) {
            if ($message['event_type'] === 'TRANSACTION.SUCCESS') {
                // 处理支付成功逻辑
                $orderNo = $message['out_trade_no'];
                // TODO: 更新订单状态
            }
            return $next($message);
        })->serve();
    }
}
